/**
*
* @author Anastasiya
*
*/

#include "util.h"
#include <direct.h>
#include <windows.h>
#include <direct.h>
#include <cstdio>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

using namespace std;

namespace utl{

	string numberToString(const int number){
		stringstream ss;
		ss << number;
		return ss.str();
	}

	string timeToString(const ULONGLONG number){

		__int64 ms = number % 1000;
		__int64 s = number / 1000;

		stringstream ss;
		if(s > 0){
			ss << s;
			ss << TIME_POSTFIX_SEC;
		}
		ss << ms;
		ss << TIME_POSTFIX_MILLISEC;
		return ss.str();
	}
	void changeCurrentDirToInput(const string inputPath){
		_chdir(inputPath.c_str());
	}

	PathType testPathType(const string path){
		struct _stat buf;
		int result = _stat(path.c_str(), &buf);
		if(result != 0){
			return NOT_EXISTS;
		}else{
			return buf.st_mode & _S_IFDIR ? IS_DIR : IS_FILE;
		}
	}

	string createGraphNameForAlgorithm(const string inputGraphFileName, const string algorithmName){
		int dotIndex = inputGraphFileName.find_first_of('.');
		string newGraphName = inputGraphFileName.substr(0, dotIndex).append("_");
		newGraphName = newGraphName.append(algorithmName);
		newGraphName = newGraphName.append(inputGraphFileName.substr(dotIndex));
		return newGraphName;
	}

	ULONGLONG calculateTimeDifference(const SYSTEMTIME startTime, const SYSTEMTIME endTime){
		ULONGLONG startTimeInMs = systemTimeInMs(startTime);
		ULONGLONG endTimeInMs = systemTimeInMs(endTime);

		return endTimeInMs - startTimeInMs;
	}

	ULONGLONG systemTimeInMs(const SYSTEMTIME time){
		FILETIME fileTime;
		SystemTimeToFileTime(&time, &fileTime);

		ULARGE_INTEGER uliTime;
		uliTime.LowPart = fileTime.dwLowDateTime;
		uliTime.HighPart = fileTime.dwHighDateTime;

		ULONGLONG timeInMs(uliTime.QuadPart / 1000);
		return timeInMs;
	}




	string getFileNameByPath(const string filePath){
		int lastSlash = filePath.find_last_of(SLASH);
		return filePath.substr(lastSlash + 1);
	}

	string getDirectoryByPath(const string filePath){
		int lastSlash = filePath.find_last_of(SLASH);
		return filePath.substr(0, lastSlash);
	}
	string removeLastSlash(string s){
		unsigned int lastNonSlashIndex = s.find_last_not_of(SLASH);
		if(lastNonSlashIndex != string::npos){
			return s.substr(0, lastNonSlashIndex + 1);
		}
		return s;
	}
}